package com.ben.multiple.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Ben
 * @date 2020/10/31
 */
public class SystemClock {
    private static final int PERIOD = 1;
    private static final int INITIAL_DELAY = 1;
    private static final AtomicLong TIME = new AtomicLong(System.currentTimeMillis());

    static {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r, "System Clock");
            thread.setDaemon(true);
            return thread;
        });
        executor.scheduleAtFixedRate(() -> {
            TIME.set(System.currentTimeMillis());
        }, INITIAL_DELAY, PERIOD, TimeUnit.MILLISECONDS);
    }

    public static Long now() {
        return TIME.get();
    }
}
